package com.li.demo;

import org.apache.xmlbeans.impl.common.ReaderInputStream;

import java.io.*;

/**
 * @author lixiang
 * @version 1.0
 * @ClassName FileOperation
 * @Description: 文件操作
 * @date 2019/4/4 14:13
 */
public class FileOperation {

    public static void main(String[] args) throws IOException {
//        checkFileOrDir();
//        getInputStream();
        getOutPutStream();
    }

    /**
     * 判断文件、文件夹是否存在
     */
    public static void checkFileOrDir() {
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();

        File file = new File("C:\\Users\\muziy\\Desktop\\demo");
        if (file.exists()) {
            System.out.println("文件存在");
            // 删除文件
//            file.delete();
        } else {
            // 创建多级文件夹
            file.mkdirs();
        }

        if (file.isDirectory()) {
            System.out.println("目录是文件夹");
        }
    }

    /**
     * 获取文件至输入流
     */
    public static void getInputStream() throws IOException {
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        System.out.println(path);
        // 获取文件
        File file = new File(path + "static/number.txt");
        if (file.exists()) {
            System.out.println("文件存在");
            // 获取字节流
            InputStream is = new FileInputStream(file);
            // 转为字符流
            InputStreamReader reader = new InputStreamReader(is);
            // 进行缓存读取
            BufferedReader br = new BufferedReader(reader);
            String str = null;
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
        }
    }


    /**
     * 获取文件至输出流
     */
    public static void getOutPutStream() throws IOException {
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        System.out.println(path);
        // 获取文件
        File file = new File(path + "static/number.txt");
        if (file.exists()) {
            System.out.println("文件存在");
            // 获取字节流
            InputStream is = new FileInputStream(file);
            // 缓存
            BufferedInputStream bis = new BufferedInputStream(is);

            // 输出文件至
            File outDir = new File(path + "static/upload/");
            if (!outDir.exists()) {
                outDir.mkdirs();
            }
            File outPath = new File(outDir.getPath() + "/" + file.getName());
            // 字节输出流
            OutputStream os = new FileOutputStream(outPath);
            // 缓存
            BufferedOutputStream bos = new BufferedOutputStream(os);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
                bos.flush();
            }
            bos.close();
            os.close();
            bis.close();
            is.close();
        }
    }
}
